// const baseUrl = 'http://192.168.110.21:8088/api/v1'; //杨建
// const ImageUrl = 'http://192.168.110.21:8088/'; //杨建

// const baseUrl = 'http://192.168.110.17:8088/api/v1'; //赵博士
// const ImageUrl = 'http://192.168.110.17:8088/'; //赵博士
//     
// const baseUrl = 'https://dicine.gfwlest.com/api/v1'; 

 
const baseUrl = 'https://zhaoyao.zhaoyaobaodian.cn/api/v1';// 正式服务器
const ImageUrl = 'https://zhaoyao.zhaoyaobaodian.cn/'; //正式服务器
 
  
// const baseUrl = 'http://testzhaoyao.zhaoyaobaodian.cn/api/v1';//测试服务器 139.196.12.215
// const ImageUrl = 'http://testzhaoyao.zhaoyaobaodian.cn/'; //测试服务器

//免登录的url  
const  avoid_login_urls= ['/tencent/auth/userSig'
,'/setting/getDoctorAuth','/share/my','/notice/listGroup','/user/info','/notice/noReadCount'];
 

const uploadImg = (filePath,callback)=>{
				let _this = this 
				uni.uploadFile({
					// url: 'https://dicine.gfwlest.com/api/v1/image/upload', 
					url: baseUrl + '/image/upload',
					filePath: filePath,
					name: 'files',
					header: {
						'token':uni.getStorageSync("token"),
						// 'Content-Type': 'application/x-www-form-urlencoded'
					},
					formData: {
						'user': 'test'
					},
					success: (uploadFileRes) => { 
						  var imgData =  JSON.parse(uploadFileRes.data.replace('\\','')).data[0]
						 callback(imgData);
					}
				});
		    };

const service = (url, method, data) => {
	const token = uni.getStorageSync("token");
	return new Promise((resolve, reject) => {
		let header = {
			 
				'Content-Type': 'application/x-www-form-urlencoded'
			};
		let _this = this;
		
		if (token) {
			header['token'] =token;
		} else {
			// uni.navigateTo({
			// 	url: '/pages/login/login'
			// })
			// resolve()
		}
		if (method) {
			method = method.toUpperCase(); //小写改为大写
		}
		uni.request({
			url: baseUrl + url,
			method: method || "GET",
			header: header,
			data: data,
			success: response => {
				if(response.data.code == 200){
					resolve(response.data)
				}else if(response.data.code == 503){
					resolve(response.data)
				}
				else if(response.data.code == 506){
					
						uni.navigateTo({
							url: '/pages/login/login'
						})
					
					reject()
				}else if(response.data.code == 532){
					var avoid_login = false; //true 免登录
					avoid_login_urls.map((item)=>{
						if(item == url){
							avoid_login = true;
						}
					})
					if(avoid_login != true){
						// uni.navigateBack({
							
						// })
						//禁止游客访问
						uni.showModal({
						    title: '你还没有登录',
						    content: '登录App体验更多精彩',
							confirmText:'立即登录',
							cancelText:'关闭',
						    success: function (res) {
						        if (res.confirm) {
						            console.log('用户点击确定');
									uni.navigateTo({
										url: '/pages/login/login'
									})
						        } else if (res.cancel) {
						            console.log('用户点击取消');
						        }
						    }
						});
						
					
					}
					
					reject()
				}
				
				else if(response.data.code == 518){
					//设备在其他地方被登录
					uni.showModal({
					    title: '提示',
						showCancel:false,
					    content: response.data.message,
					    success: function (res) {
					        if (res.confirm) {
					            uni.navigateTo({
					            	url: '/pages/login/login'
					            })
					        }
					    }
					});
					reject()
				}else if(response.data.code == 511){
					//数据被删除
					uni.redirectTo({
						url:'/pages/request/requestDataErr?type=3'
					})
					reject()
				}
				else  if(response.data.code == 500 || response.data.code == 501) {
					//服务器错误
					uni.redirectTo({
						url:'/pages/request/requestDataErr?type=2'
					})
					reject()
				}else{
					uni.showToast({
						title: response.data.message,
						icon:'none',
						duration: 2000
					});
					reject(response.data)
				}
			},
			fail: (e) => {
				console.log("网络请求fail:" + JSON.stringify(e));
				 
			   uni.navigateTo({
			   	url:'/pages/request/requestFail'
			   })
			}
		})
	})
}


//腾讯云IM 聊天
const IMLogin = (_this) => {
	return new Promise((resolve,reject)=>{
		// if(uni.getStorageSync("userSig")){
		// 	resolve() 
		// }else{
			service('/tencent/auth/userSig','get',{imUserId:uni.getStorageSync("imUserId")}).then(res=>{
				// uni.setStorageSync("userSig",res.data.userSig);
				let promise = _this.tim.login({userID: uni.getStorageSync("imUserId"), userSig: res.data.userSig});
				promise.then(function(imResponse) {
				  console.log(imResponse.data); // 登录成功
				  // if (imResponse.data.repeatLogin === true) {
				  //   // 标识账号已登录，本次登录操作为重复登录。v2.5.1 起支持
				  //   console.log(imResponse.data.errorInfo);
				  // }
				  setTimeout(()=>{resolve()},500)
				}).catch(function(imError) {
				  console.warn('login error:', imError); // 登录失败的相关信息
				});
			})
		// }
	})
}
class Push_Message{
	 
}
class UserModel{
	
	/**
	 * 更新本地用户信息
	 * 
	 * @param {Object} data 用户数据
	 * @param {Object} isGoHome  是否跳转到首页
	 */
	update_user_token(data,isGoHome){
		uni.setStorageSync('token', data.token);
		uni.setStorageSync('uid', data.uid);
		uni.setStorageSync('imUserId', data.imUserId);
		if(isGoHome){
			setTimeout(()=>{
				uni.switchTab({
					url: '/pages/index/index'
				});
			},100)
		}
	}
	is_tourists_login(){
		var token = uni.getStorage({
			key:'token'
		})
 
		var imUserId = uni.getStorageSync('imUserId')
		if(imUserId == 'guestRegister'){
	       return true;
		}else{
			 return false;
		}
	}
	//游客登录
	tourists_login(){
	
		if(this.is_tourists_login()){
			uni.showModal({
			    title: '你还没有登录',
			    content: '登录App体验更多精彩',
				confirmText:'立即登录',
				cancelText:'关闭',
			    success: function (res) {
			        if (res.confirm) {
			            console.log('用户点击确定');
						uni.navigateTo({
							url: '/pages/login/login'
						})
			        } else if (res.cancel) {
			            console.log('用户点击取消');
			        }
			    }
			});
			return true;
		}
		
	}
}

 class IM_Server{
	
   load_msg_count (_this){
	 
	  // let _this = this; 
	  _this.IMLogin(_this).then(res => {
	  	   let promise = _this.tim.getConversationList();
	  		promise.then(function(imResponse) {
	  				let arr = imResponse.data.conversationList;
	  				var unreadCount = 0;
					
					
	  				for (let i = 0; i < arr.length; i++) {
						if(arr[i].groupProfile != null){
								unreadCount +=  arr[i].unreadCount;
						}
	  					
	  					// arr[i].times = _this.timestampToTime(arr[i].lastMessage.lastTime);
	  				}
					 service('/notice/noReadCount','get',[]).then(res=>{
						// console.log(res)
						unreadCount += res.data;
						if(unreadCount > 0 ){
							if(unreadCount>99){
								unreadCount = '99+';
							}
							//新版本改版，暂时隐藏 角标、
							// uni.setTabBarBadge({
							//   index: 2,
							//   text:  unreadCount.toString(),
							//   fail:(e)=>{
							// 	console.log(e)  
							//   }
							// })
						}else{
							uni.removeTabBarBadge({
								index:2
							})
						}
						 
					}) 
	  				console.log(arr, 'load_msg_count');
	  				// _this.msgList = arr;
	  			})
	  			.catch(function(imError) {
	  				console.warn('getGroupList error:', imError); // 获取群组列表失败的相关信息
	  			});				
	  					
	  });
	 
	}
}
const customer_server = function (){
	uni.navigateTo({
		url: '/components/bytedesk_kefu/chat-kf?wid=' +
			'202102051511592de770d3d929343dca328eb3e3c4a3a16' + '&type=workGroup&aid=&nickname=' +
			this.$user?.userName + '&history=0&avatar=' + this.$user?.head,
	
	})
	console.log('customer_server')
}
 
export default {
	service,
	uploadImg,
	baseUrl,
	ImageUrl,
	IMLogin,
	IM_Server,
	Push_Message,
	UserModel,
	customer_server,
};
